package com.rabbiter.oes.controller;

import com.rabbiter.oes.entity.*;
import com.rabbiter.oes.serviceimpl.FillQuestionServiceImpl;
import com.rabbiter.oes.serviceimpl.JudgeQuestionServiceImpl;
import com.rabbiter.oes.serviceimpl.MultiQuestionServiceImpl;
import com.rabbiter.oes.serviceimpl.PaperServiceImpl;
import com.rabbiter.oes.util.ApiResultHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class PaperController {

    @Autowired
    private PaperServiceImpl paperService;

    @Autowired
    private JudgeQuestionServiceImpl judgeQuestionService;

    @Autowired
    private MultiQuestionServiceImpl multiQuestionService;

    @Autowired
    private FillQuestionServiceImpl fillQuestionService;
    @GetMapping("/papers")
    public ApiResult<PaperManage> findAll() {
       ApiResult res =  ApiResultHandler.buildApiResult(200,"请求成功",paperService.findAll());
       return  res;
    }

    @GetMapping("/papers/user-paper")
    public Map<Integer, List<?>> getUserPaper(
            @RequestParam String paperId,
            @RequestParam Long userId) {
        System.out.println("Map11111=>");
        String PaperId=paperId;
        List<MultiQuestion> multiQuestions = multiQuestionService.findByExamCodeAndUserId(PaperId, userId);
        List<FillQuestion> fillQuestions = fillQuestionService.findByExamCodeAndUserId(PaperId, userId);
        List<JudgeQuestion> judgeQuestions = judgeQuestionService.findByExamCodeAndUserId(PaperId, userId);

        Map<Integer, List<?>> map = new HashMap<>();
        map.put(1,multiQuestions);
        map.put(2,fillQuestions);
        map.put(3,judgeQuestions);
        System.out.println("map=>"+map);
        return map;
    }

//    @GetMapping("/paper/{paperId}")
//    public Map<Integer, List<?>> findById(@PathVariable("paperId") String paperId) {
//        System.out.println("Map222222=>");
//        List<MultiQuestion> multiQuestionRes = multiQuestionService.findByIdAndType(paperId);   //选择题题库 1
//        List<FillQuestion> fillQuestionsRes = fillQuestionService.findByIdAndType(paperId);     //多选题题库 2
//        List<JudgeQuestion> judgeQuestionRes = judgeQuestionService.findByIdAndType(paperId);   //判断题题库 3
//        Map<Integer, List<?>> map = new HashMap<>();
//        map.put(1,multiQuestionRes);
//        map.put(2,fillQuestionsRes);
//        map.put(3,judgeQuestionRes);
//        return  map;
//    }

    @PostMapping("/paperManage")
    public ApiResult add(@RequestBody PaperManage paperManage) {
        System.out.println("paperManage:"+paperManage);
        int res = paperService.add(paperManage);
        if (res != 0) {
            return ApiResultHandler.buildApiResult(200,"添加成功",res);
        }
        return ApiResultHandler.buildApiResult(400,"添加失败",res);
    }

    @PostMapping("/paperManage/add")
    public ApiResult addPaperQuestions(@RequestBody List<PaperManage> paperData) {
        if (paperData == null || paperData.isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "没有数据需要插入", null);
        }
        try {
            System.out.println("------------------paperData------------"+paperData);
            int result = paperService.batchInsert(paperData);
            if (result > 0) {
                return ApiResultHandler.buildApiResult(200, "题目插入成功", result);
            } else {
                return ApiResultHandler.buildApiResult(500, "题目插入失败", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultHandler.buildApiResult(500, "服务器内部错误", null);
        }
    }
    /**
     * 删除试卷中的某条试题
     *
     * @param paperId 试卷id
     * @param type 题目类型。1选择，2填空，3判断
     * @param questionId 题目id
     */
    @GetMapping("/paper/delete/{paperId}/{type}/{questionId}")
    public ApiResult delete(
            @PathVariable("paperId") String paperId,
            @PathVariable("type") String type,
            @PathVariable("questionId") String questionId
    ) {
        paperService.delete(paperId, type, questionId);
        return ApiResultHandler.buildApiResult(200,"删除成功", null);
    }

    @PostMapping("/generate")
    public ApiResult<String> generatePaper(
            @RequestParam String originalPaperId,
            @RequestParam String userId,
            @RequestBody List<PaperManage> questions) {

        if (originalPaperId == null || userId == null) {
            return ApiResultHandler.buildApiResult(500,"参数缺失：originalPaperId 或 userId",null);
        }

        if (questions == null || questions.isEmpty()) {
            return ApiResultHandler.buildApiResult(500,"题目不能为空",null);
        }

        // ✅ 1. 生成唯一 paperId：原ID_用户ID_时间戳
        String uniquePaperId = generateUniquePaperId(originalPaperId, userId);

        // ✅ 2. 绑定新 paperId
        for (PaperManage q : questions) {
            q.setPaperId(uniquePaperId);
        }

        // ✅ 3. 批量插入
        try {
            paperService.saveBatch(questions);
            return ApiResultHandler.buildApiResult(200,"组卷成功",uniquePaperId); // 返回新 paperId
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultHandler.buildApiResult(500,"组卷失败：" ,e.getMessage());
        }
    }

    // ==================== 查询：获取某份试卷的所有题目 ====================

    /**
     * 根据 paperId 获取所有题目（用于答题页）
     */
    @GetMapping("/questions")
    public ApiResult<List<PaperManage>> getQuestions(@RequestParam String paperId) {
        if (paperId == null || paperId.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(500,"paperId 不能为空",null);
        }

        List<PaperManage> questions = paperService.getQuestionsByPaperId(paperId);
        return ApiResultHandler.success(questions);
    }

    // ==================== 工具方法 ====================

    /**
     * 生成唯一 paperId
     * 格式：originalPaperId_userId_timestamp
     */
    private String generateUniquePaperId(String originalPaperId, String userId) {
        return originalPaperId + "_" + userId + "_" + System.currentTimeMillis();
    }
    @GetMapping("/paperManage/exists")
    public ApiResult<Boolean> hasUserPaper(
            @RequestParam String paperId,
            @RequestParam String userId) {

        if (paperId == null || paperId.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "paperId 不能为空", false);
        }
        if (userId == null || userId.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "userId 不能为空", false);
        }
        System.out.println("--------------------------paperId=>"+paperId+"userId=>"+userId+"---------------------");
        try {
            boolean exists = paperService.hasUserPaper(paperId, userId);
            return ApiResultHandler.success(exists); // code=200, data=true/false
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultHandler.buildApiResult(500, "服务器内部错误", false);
        }
    }

    @DeleteMapping("/paperManage/clear")
    public ApiResult clearUserPaper(@RequestParam String paperId, @RequestParam String userId) {
        if (paperId == null || paperId.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "paperId 不能为空", null);
        }
        if (userId == null || userId.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "userId 不能为空", null);
        }

        try {
            int count = paperService.clearUserPaper(paperId, userId);
            return ApiResultHandler.buildApiResult(200, "成功清除 " + count + " 道题目", count);
        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultHandler.buildApiResult(500, "清除失败：服务器内部错误", null);
        }
    }
    
}
